const { pool } = require('../config/db');
const { success, error } = require('../utils/response');
const moment = require('moment');

// ===== 用户端 =====

// 获取用户通知列表
exports.getNotifications = async (req, res, next) => {
  try {
    const userId = req.userId;
    const { page = 1, limit = 20, is_read, type } = req.query;
    const offset = (page - 1) * limit;

    let whereClause = 'WHERE user_id = ?';
    let params = [userId];

    if (is_read !== undefined) {
      whereClause += ' AND is_read = ?';
      params.push(is_read === '1' ? 1 : 0);
    }

    if (type) {
      whereClause += ' AND type = ?';
      params.push(type);
    }

    const [notifications] = await pool.query(`
      SELECT
        id,
        type,
        title,
        content,
        related_id,
        is_read,
        send_time,
        read_time
      FROM notifications
      ${whereClause}
      ORDER BY send_time DESC
      LIMIT ? OFFSET ?
    `, [...params, parseInt(limit), offset]);

    const [total] = await pool.query(`
      SELECT COUNT(*) as count FROM notifications ${whereClause}
    `, params);

    success(res, {
      notifications,
      pagination: {
        current: parseInt(page),
        limit: parseInt(limit),
        total: total[0].count,
        pages: Math.ceil(total[0].count / limit)
      }
    });
  } catch (err) {
    next(err);
  }
};

// 获取未读通知数量
exports.getUnreadCount = async (req, res, next) => {
  try {
    const userId = req.userId;

    const [result] = await pool.query(
      'SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = 0',
      [userId]
    );

    success(res, { unreadCount: result[0].count });
  } catch (err) {
    next(err);
  }
};

// 标记通知为已读
exports.markAsRead = async (req, res, next) => {
  try {
    const { id } = req.params;
    const userId = req.userId;

    // 检查通知是否存在且属于当前用户
    const [notifications] = await pool.query(
      'SELECT id FROM notifications WHERE id = ? AND user_id = ?',
      [id, userId]
    );

    if (notifications.length === 0) {
      return error(res, '通知不存在', 404);
    }

    await pool.query(
      'UPDATE notifications SET is_read = 1, read_time = NOW() WHERE id = ?',
      [id]
    );

    success(res, { id }, '标记成功');
  } catch (err) {
    next(err);
  }
};

// 标记所有通知为已读
exports.markAllAsRead = async (req, res, next) => {
  try {
    const userId = req.userId;

    await pool.query(
      'UPDATE notifications SET is_read = 1, read_time = NOW() WHERE user_id = ? AND is_read = 0',
      [userId]
    );

    success(res, {}, '全部标记成功');
  } catch (err) {
    next(err);
  }
};

// 删除通知
exports.deleteNotification = async (req, res, next) => {
  try {
    const { id } = req.params;
    const userId = req.userId;

    // 检查通知是否存在且属于当前用户
    const [notifications] = await pool.query(
      'SELECT id FROM notifications WHERE id = ? AND user_id = ?',
      [id, userId]
    );

    if (notifications.length === 0) {
      return error(res, '通知不存在', 404);
    }

    await pool.query('DELETE FROM notifications WHERE id = ?', [id]);

    success(res, { id }, '删除成功');
  } catch (err) {
    next(err);
  }
};

// 清空已读通知
exports.clearReadNotifications = async (req, res, next) => {
  try {
    const userId = req.userId;

    await pool.query(
      'DELETE FROM notifications WHERE user_id = ? AND is_read = 1',
      [userId]
    );

    success(res, {}, '清空成功');
  } catch (err) {
    next(err);
  }
};

// ===== 系统内部方法（用于发送通知）=====

// 发送通知
exports.sendNotification = async (userId, type, title, content, relatedId = null) => {
  try {
    await pool.query(`
      INSERT INTO notifications (user_id, type, title, content, related_id)
      VALUES (?, ?, ?, ?, ?)
    `, [userId, type, title, content, relatedId]);
    return true;
  } catch (err) {
    console.error('发送通知失败:', err);
    return false;
  }
};

// 批量发送通知
exports.sendBatchNotifications = async (userIds, type, title, content, relatedId = null) => {
  try {
    if (!userIds || userIds.length === 0) return false;

    const values = userIds.map(userId => [userId, type, title, content, relatedId]);
    await pool.query(`
      INSERT INTO notifications (user_id, type, title, content, related_id)
      VALUES ?
    `, [values]);
    return true;
  } catch (err) {
    console.error('批量发送通知失败:', err);
    return false;
  }
};

// 发送到期提醒
exports.sendDueReminder = async (borrowRecordId, userId, bookName, dueDate) => {
  const dueDays = moment(dueDate).diff(moment(), 'days');
  const title = '图书即将到期';
  const content = `您借阅的《${bookName}》将在${dueDays}天后到期，请及时归还或续借。`;
  return await exports.sendNotification(userId, 'borrow_due', title, content, borrowRecordId);
};

// 发送逾期通知
exports.sendOverdueNotice = async (borrowRecordId, userId, bookName, overdueDays) => {
  const title = '图书已逾期';
  const content = `您借阅的《${bookName}》已逾期${overdueDays}天，请尽快归还，避免产生更多罚款。`;
  return await exports.sendNotification(userId, 'overdue', title, content, borrowRecordId);
};

// 发送预约可借通知
exports.sendReservationAvailableNotice = async (reservationId, userId, bookName) => {
  const title = '预约图书已可借';
  const content = `您预约的《${bookName}》已可借阅，请在3天内前来借阅，逾期将自动取消预约。`;
  return await exports.sendNotification(userId, 'reservation_available', title, content, reservationId);
};

// 发送订单审批通知
exports.sendOrderApprovedNotice = async (orderId, userId, bookName, approved) => {
  const title = approved ? '借阅申请已通过' : '借阅申请被驳回';
  const content = approved 
    ? `您的《${bookName}》借阅申请已通过，请前往图书馆办理借阅。`
    : `您的《${bookName}》借阅申请被驳回，请联系管理员了解详情。`;
  const type = approved ? 'order_approved' : 'order_rejected';
  return await exports.sendNotification(userId, type, title, content, orderId);
};

// 发送续借审批通知
exports.sendRenewApprovedNotice = async (renewId, userId, bookName, approved) => {
  const title = approved ? '续借申请已通过' : '续借申请被驳回';
  const content = approved 
    ? `您的《${bookName}》续借申请已通过，到期时间已延长。`
    : `您的《${bookName}》续借申请被驳回，请按原到期时间归还。`;
  const type = approved ? 'renew_approved' : 'renew_rejected';
  return await exports.sendNotification(userId, type, title, content, renewId);
};

// 发送系统通知
exports.sendSystemNotice = async (userId, title, content) => {
  return await exports.sendNotification(userId, 'system', title, content);
};

// 清理旧通知（定时任务）
exports.cleanOldNotifications = async (daysToKeep = 30) => {
  try {
    const cutoffDate = moment().subtract(daysToKeep, 'days').format('YYYY-MM-DD HH:mm:ss');
    await pool.query(
      'DELETE FROM notifications WHERE is_read = 1 AND read_time < ?',
      [cutoffDate]
    );
    console.log(`清理了${daysToKeep}天前的已读通知`);
    return true;
  } catch (err) {
    console.error('清理旧通知失败:', err);
    return false;
  }
};

// 导出内部方法供其他模块使用
module.exports.sendNotification = exports.sendNotification;
module.exports.sendBatchNotifications = exports.sendBatchNotifications;
module.exports.sendDueReminder = exports.sendDueReminder;
module.exports.sendOverdueNotice = exports.sendOverdueNotice;
module.exports.sendReservationAvailableNotice = exports.sendReservationAvailableNotice;
module.exports.sendOrderApprovedNotice = exports.sendOrderApprovedNotice;
module.exports.sendRenewApprovedNotice = exports.sendRenewApprovedNotice;
module.exports.sendSystemNotice = exports.sendSystemNotice;

